var express = require('express');
var router = express.Router();
var needle = require('needle');
var uuid = require('uuid');
var WXBizDataCrypt = require('../utils/WXBizDataCrypt');
var redis = require('redis');
var Member = require('../model/Member');

router.post('/login', function(req, res) {
    console.log(req.body.code);
    var code = req.body.code;
    var APPID = 'wx0b354f336d0779d7';
    var SECRET = 'b0798c6650fe9e4e827d33ca98876e26';
    needle.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`, { parse_response: 'json' }, (err, response, body) => {
        var info = JSON.parse(body);
        // 得到了openid与session_key
        // {
        //     session_key: 'qGjCqvhMhSrS1pAq7Vyl4g==',
        //     openid: 'oN2YX0drQd-kjVwZSZFpPcnNbrh0',
        //     unionid: 'oUJ9ys4zB6SvvdxVbyVO1-ibYmfY'
        // }
        // 先产生随机数，作为redis中的key
        var key = uuid().replace(/-/g, '');
        console.log(key);
        // 写入redis
        var client = redis.createClient('6379', 'localhost');
        client.set(key, body);
        client.get(key, function(err, value) {
            console.log(value);
        });
        // 创建用户

        Member.findOneAndUpdate({
            openid: info.openid
        }, {
            openid: info.openid
        }, {
            upsert: true,
            new: true
        }, function(err, member) {
            if (err) {
                console.log(err)
                res.json({
                    code: 400,
                    msg: '登录失败'
                });
            } else {
                res.json({
                    code: 200,
                    msg: '登录成功',
                    data: {
                        thirdSession: key
                    }
                });
            }
        });

        // var pc = new WXBizDataCrypt(APPID, body.session_key)
        // var data = pc.decryptData(encryptedData , iv)
        // res.send({
        //     code: 200,
        //     msg: '登录成功',
        //     data: {
        //         key: key
        //     }
        // });
    });


});

module.exports = router;